package renpyas3.model 
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.loadingtypes.LoadingItem;
	import flash.display.Bitmap;
	import flash.events.Event;
	import org.osflash.thunderbolt.Logger;
	
	/**
	 * tries to load something from embedded assets
	 * and if it doesn't work, loads from local
	 */
	public class AssetsLoader extends BulkLoader
	{
		private var _embeds:Embeds;
		
		public function AssetsLoader(embeds:Embeds, name:String = null, numConnections:int = BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel:int = BulkLoader.DEFAULT_LOG_LEVEL) 
		{
			_embeds = embeds;
			super(name, numConnections, logLevel);
		}

		
		/**
		 * tries to get definition from embedded assets
		 */
		public function getEmbeddedObjectDefinition(pathAndFilename:String):Object
		{
			return _embeds.getEmbeddedObjectDefinition(pathAndFilename);
		}
		
		override public function add(url : * , props : Object = null ) : LoadingItem 
		{
			var classDef:Object = _embeds.getEmbeddedObjectDefinition(url);
			if (classDef == null)
			{
				var loadingItem:LoadingItem = super.add(url, props);
				loadingItem.addEventListener(BulkLoader.ERROR, handleLoadAssetIOerror);
				loadingItem.maxTries = 0;
				return loadingItem 
			}
			else
			{
				return null;
			}
		}
		
		override public function getBitmap(key : String, clearMemory : Boolean = false) : Bitmap
		{
			var classDef:Object = _embeds.getEmbeddedObjectDefinition(key)
			if (classDef == null)
			{		
				return Bitmap(_getContentAsType(key, Bitmap, clearMemory));
			}
			else
			{
				//'load' from embed
				var newBitmap:Bitmap = new classDef() as Bitmap;
				return newBitmap;
			}
		}
	
		
        private function handleLoadAssetIOerror(e:Event):void 
		{
			Logger.error("AssetsLoader::handleLoadAssetIOerror: " + (e.target as LoadingItem).url.url);
        }

	}

}